package com.gxar.marketdelivery.application.facade;

import com.gxar.marketdelivery.application.query.DeliveryHandler;
import com.gxar.marketdelivery.domain.enums.DeliveryResSlotStatus;
import com.gxar.marketdelivery.domain.factory.DeliveryFactory;
import com.gxar.marketdelivery.interfaces.web.param.DeliveryParam;
import com.gxar.marketdelivery.interfaces.web.param.MultiResSlotWithKeyParam;
import com.gxar.marketdelivery.interfaces.web.param.SingleResSlotWithKeyParam;
import com.gxar.marketdelivery.interfaces.web.result.CDeliveryResSlotResult;
import com.gxar.marketdelivery.interfaces.web.result.IResponseStatusMsg;
import com.gxar.marketdelivery.shared.model.DeliveryResSlotModel;
import com.gxar.marketdelivery.shared.utils.AssertUtils;
import com.gxar.marketdelivery.shared.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author nice
 * @version 1.0
 * @created 2023/8/2.
 */
@Service
@Slf4j
public class DeliveryFacade {

    @Autowired
    protected DeliveryHandler deliveryHandler;
    @Autowired
    protected DeliveryFactory deliveryFactory;

    public CDeliveryResSlotResult getResSlotBySlotKey(SingleResSlotWithKeyParam param) {
        return getResSlotInfo(param, param.getResSlotKey());
    }

    public List<CDeliveryResSlotResult> getResSlotBySlotKeys(MultiResSlotWithKeyParam param) {
        AssertUtils.notEmpty(param.getResSlotKeys(), IResponseStatusMsg.APIEnum.PARAM_ERROR, "资源位标识列表为空");
        return multiGetResSlotInfos(param, param.getResSlotKeys());
    }

    private CDeliveryResSlotResult getResSlotInfo(DeliveryParam request, String resSlotKey) {
        DeliveryResSlotModel resSlotModel = deliveryFactory.getResSlotByResSlotKey(resSlotKey);
        // 不存在或已关闭，不返回
        if (resSlotModel == null || DeliveryResSlotStatus.CLOSE.equalByCode(resSlotModel.getResSlotStatus())) {
            return null;
        }
        return deliveryHandler.getResSlot(request, resSlotModel);
    }

    private List<CDeliveryResSlotResult> multiGetResSlotInfos(DeliveryParam request, List<String> resSlotKeys) {
        if (CollectionUtils.isEmpty(resSlotKeys)) {
            return Collections.emptyList();
        }
        List<DeliveryResSlotModel> resSlotModels = deliveryFactory.getResSlotByResSlotKeys(resSlotKeys);
        if (CollectionUtils.isEmpty(resSlotModels)) {
            return Collections.emptyList();
        }
        resSlotModels = resSlotModels.stream()
                .filter(resSlotModel -> DeliveryResSlotStatus.OPEN.equalByCode(resSlotModel.getResSlotStatus()))
                .collect(Collectors.toList());
        return deliveryHandler.multiGetResSlot(request, resSlotModels);
    }
}
